import {$fetch} from "ofetch";

const errorCode = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    'default': '系统未知错误，请反馈给管理员'
}

const fetch = $fetch.create({
    // 请求拦截器
    async onRequest({options}) {
        const {getToken} = useUtils().AuthUtils;
        const {loginStatus, token} = useStoreToRefs(useStores.user());
        options.baseURL = useRuntimeConfig().public.apiBase;
        if (getToken() || loginStatus.value) {
            options.headers = new Headers(options.headers);
            options.headers.set("Authorization", 'Bearer ' + (getToken() || token.value || ""));
        }
    },
    // 响应拦截
    onResponse({response}) {
        const data = response._data;
        const code = data.code;
        const responseType = response.headers.get('content-type');
        // 二进制数据则直接返回
        if (responseType === 'blob' || responseType === 'arraybuffer') {
            return data;
        }
        // @ts-ignore
        const msg = errorCode[code + ''] || data.msg || errorCode['default']
        if (code === 401) {
            // TODO 清空用户登录状态
            useStores.user().clear();
            throw createError({
                statusCode: data.code,
                statusMessage: "无效的会话，或者会话已过期，请重新登录：请求地址：" + response.url,
                fatal: true
            });
        } else if (code === 500) {
            useUtils().ModalUtils.msgError(msg);
            throw createError({
                statusCode: data.code,
                statusMessage: "服务器发生错误：" + msg + " 请求地址：" + response.url,
                fatal: true
            });
        } else if (code === 601) {
            useUtils().ModalUtils.msgWarning(msg);
            return Promise.reject('error');
        } else if (code !== 200) {
            useUtils().ModalUtils.msgError(msg);
            return Promise.reject(data);
        }
        return data;
    },
    // 错误处理
    onResponseError(error) {
        if (error?.response?._data) {
            modal.msgError(error?.response?._data.msg || errorCode['default']);
        } else {
            modal.msgError("请求超时，服务器无响应");
        }
        return Promise.reject(error?.response?._data ?? null);
    },
});

export default {
    get: (url: string, params?: any, headers?: any) => {
        return fetch(url, {
            method: "get",
            params,
            headers
        });
    },
    post: (url: string, params?: any, headers?: any) => {
        return fetch(url, {
            method: "post",
            body: params,
            headers
        });
    },
    delete: (url: string, params?: any, headers?: any) => {
        return fetch(url, {
            method: "delete",
            body: params,
            headers
        });
    },
    put: (url: string, params?: any, headers?: any) => {
        return fetch(url, {
            method: "put",
            body: params,
            headers
        });
    }
};